<?php

namespace App\Console\Commands;

use App\Models\Permission;
use App\Models\Role;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Hash;

class AppInit extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'app:init';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '系统初始化命令';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        if (!User::whereUsername('admin')->exists()) {
            User::create([
                'username' => 'admin',
                'realname' => '超级管理员',
                'password' => Hash::make("admin")
            ]);
            $this->info("系统管理员创建成功");
        }

        Permission::query()->delete();
        // 初始化权限
        $model = new Permission();
        $permissions = $model->defaultPermission();

        $data = [];
        foreach ($permissions as $item) {
            foreach ($item['children'] as $val) {
                array_push($data, [
                    'name' => $val['slug'],
                    'slug' => $val['name'],
                    'guard_name' => 'api',
                    'created_at' => Carbon::now(),
                    'updated_at' => Carbon::now(),
                ]);
            }
        }
        Permission::insert($data);

        $role = Role::updateOrCreate(['name' => '超级管理员', 'desc' => '超级管理员']);
        $user = User::whereUsername("admin")->first();
        if ($user)  {
            $user->assignRole($role);
        }
        return 0;
    }
}
